﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;



namespace Defector
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public SqlConnection con;

        public int userID;
        public String firstName;
        public String lastName;

        public MainWindow()
        {
            
            InitializeComponent();
            
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem mi = e.Source as MenuItem;
            switch (mi.Name)
            {

                case "Exit":
                    {
                        Environment.Exit(0);
                        break;
                    }
                case "logOff":
                    {
                        Login login = new Login();
                        login.Show();
                        Application.Current.MainWindow = login;
                        this.Close();
                        break;
                    }
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            bottomStatusBar.Content += firstName + " " + lastName;

            //Load data into your defects grid
            SqlCommand cmd = new SqlCommand("SELECT dbo.Trouble_Report.Trouble_Report_Id AS ID, dbo.Trouble_Report.Priority, dbo.Softwares.Software_Name AS Software, dbo.Trouble_Report.Headline, dbo.Trouble_Report.Description FROM dbo.Trouble_Report INNER JOIN dbo.People ON dbo.Trouble_Report.PersonId = dbo.People.Id INNER JOIN dbo.Softwares ON dbo.Trouble_Report.SoftwareSoftware_Id = dbo.Softwares.Software_Id WHERE (dbo.Trouble_Report.Status = 1) AND (dbo.People.Id = 1)", con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet yourDefects = new DataSet();
            adapter.Fill(yourDefects);
            yourDefectsDataGrid.DataContext = yourDefects.Tables[0].DefaultView;
            

            Defector.DefectEntitiesDataSet defectEntitiesDataSet = ((Defector.DefectEntitiesDataSet)(this.FindResource("defectEntitiesDataSet")));
            // Load data into the table Trouble_Report. You can modify this code as needed.
            Defector.DefectEntitiesDataSetTableAdapters.Trouble_ReportTableAdapter defectEntitiesDataSetTrouble_ReportTableAdapter = new Defector.DefectEntitiesDataSetTableAdapters.Trouble_ReportTableAdapter();
            defectEntitiesDataSetTrouble_ReportTableAdapter.Fill(defectEntitiesDataSet.Trouble_Report);
            System.Windows.Data.CollectionViewSource trouble_ReportViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("trouble_ReportViewSource")));
            trouble_ReportViewSource.View.MoveCurrentToFirst();
            // Load data into the table Open_Orders. You can modify this code as needed.
            Defector.DefectEntitiesDataSetTableAdapters.Open_OrdersTableAdapter defectEntitiesDataSetOpen_OrdersTableAdapter = new Defector.DefectEntitiesDataSetTableAdapters.Open_OrdersTableAdapter();
            defectEntitiesDataSetOpen_OrdersTableAdapter.Fill(defectEntitiesDataSet.Open_Orders);
            System.Windows.Data.CollectionViewSource open_OrdersViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("open_OrdersViewSource")));
            open_OrdersViewSource.View.MoveCurrentToFirst();
            // Load data into the table Closed_Orders. You can modify this code as needed.
            Defector.DefectEntitiesDataSetTableAdapters.Closed_OrdersTableAdapter defectEntitiesDataSetClosed_OrdersTableAdapter = new Defector.DefectEntitiesDataSetTableAdapters.Closed_OrdersTableAdapter();
            defectEntitiesDataSetClosed_OrdersTableAdapter.Fill(defectEntitiesDataSet.Closed_Orders);
            System.Windows.Data.CollectionViewSource closed_OrdersViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("closed_OrdersViewSource")));
            closed_OrdersViewSource.View.MoveCurrentToFirst();
            // Load data into the table New_Orders. You can modify this code as needed.
            Defector.DefectEntitiesDataSetTableAdapters.New_OrdersTableAdapter defectEntitiesDataSetNew_OrdersTableAdapter = new Defector.DefectEntitiesDataSetTableAdapters.New_OrdersTableAdapter();
            defectEntitiesDataSetNew_OrdersTableAdapter.Fill(defectEntitiesDataSet.New_Orders);
            System.Windows.Data.CollectionViewSource new_OrdersViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("new_OrdersViewSource")));
            new_OrdersViewSource.View.MoveCurrentToFirst();
            // Glossary Data
            Defector.DefectEntitiesDataSet.GlossaryDataTable glossaryDataSet = new Defector.DefectEntitiesDataSet.GlossaryDataTable();
            Defector.DefectEntitiesDataSetTableAdapters.GlossaryTableAdapter glossaryAdapter = new Defector.DefectEntitiesDataSetTableAdapters.GlossaryTableAdapter();
            System.Windows.Data.CollectionViewSource glossaryViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("glossaryViewSource")));
            


            cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT * FROM Softwares";
            
            adapter.SelectCommand = cmd;

            DataSet ds = new DataSet();
            try
            {
                adapter.Fill(ds, "Software");

                DataRow nRow = ds.Tables["Software"].NewRow();

                //Binding the data to the combobox.
                softwareComboBox.DataContext = ds.Tables["Software"].DefaultView;

                //To display category name (DisplayMember in Visual Studio 2005)
                 softwareComboBox.DisplayMemberPath =
                    ds.Tables["Software"].Columns["Software_Name"].ToString();
                //To store the ID as hidden (ValueMember in Visual Studio 2005)
                 softwareComboBox.SelectedValuePath =
                    ds.Tables["Software"].Columns["Software_Id"].ToString();

            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while loading software data.");
            }

        }

        private void newOrdersRefresh_Click(object sender, RoutedEventArgs e)
        {
            // Load data into the table Open_Orders. You can modify this code as needed.
            Defector.DefectEntitiesDataSet defectEntitiesDataSet = ((Defector.DefectEntitiesDataSet)(this.FindResource("defectEntitiesDataSet")));
            Defector.DefectEntitiesDataSetTableAdapters.New_OrdersTableAdapter defectEntitiesDataSetNew_OrdersTableAdapter = new Defector.DefectEntitiesDataSetTableAdapters.New_OrdersTableAdapter();
            defectEntitiesDataSetNew_OrdersTableAdapter.Fill(defectEntitiesDataSet.New_Orders);
            System.Windows.Data.CollectionViewSource new_OrdersViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("new_OrdersViewSource")));
            new_OrdersViewSource.View.MoveCurrentToFirst();
        }

        private void openOrdersRefresh_Click(object sender, RoutedEventArgs e)
        {
            Defector.DefectEntitiesDataSet defectEntitiesDataSet = ((Defector.DefectEntitiesDataSet)(this.FindResource("defectEntitiesDataSet")));
            // Load data into the table Open_Orders. You can modify this code as needed.
            Defector.DefectEntitiesDataSetTableAdapters.Open_OrdersTableAdapter defectEntitiesDataSetOpen_OrdersTableAdapter = new Defector.DefectEntitiesDataSetTableAdapters.Open_OrdersTableAdapter();
            defectEntitiesDataSetOpen_OrdersTableAdapter.Fill(defectEntitiesDataSet.Open_Orders);
            System.Windows.Data.CollectionViewSource open_OrdersViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("open_OrdersViewSource")));
            open_OrdersViewSource.View.MoveCurrentToFirst();
        }

        private void closedOrdersRefresh_Click(object sender, RoutedEventArgs e)
        {
            Defector.DefectEntitiesDataSet defectEntitiesDataSet = ((Defector.DefectEntitiesDataSet)(this.FindResource("defectEntitiesDataSet")));
            // Load data into the table Closed_Orders. You can modify this code as needed.
            Defector.DefectEntitiesDataSetTableAdapters.Closed_OrdersTableAdapter defectEntitiesDataSetClosed_OrdersTableAdapter = new Defector.DefectEntitiesDataSetTableAdapters.Closed_OrdersTableAdapter();
            defectEntitiesDataSetClosed_OrdersTableAdapter.Fill(defectEntitiesDataSet.Closed_Orders);
            System.Windows.Data.CollectionViewSource closed_OrdersViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("closed_OrdersViewSource")));
            closed_OrdersViewSource.View.MoveCurrentToFirst();
        }

        private void yourDefectsRefresh_Click(object sender, RoutedEventArgs e)
        {
            //Load data into your defects grid
            SqlCommand cmd = new SqlCommand("SELECT dbo.Trouble_Report.Trouble_Report_Id AS ID, dbo.Trouble_Report.Priority, dbo.Softwares.Software_Name AS Software, dbo.Trouble_Report.Headline, dbo.Trouble_Report.Description FROM dbo.Trouble_Report INNER JOIN dbo.People ON dbo.Trouble_Report.PersonId = dbo.People.Id INNER JOIN dbo.Softwares ON dbo.Trouble_Report.SoftwareSoftware_Id = dbo.Softwares.Software_Id WHERE (dbo.Trouble_Report.Status = 1) AND (dbo.People.Id = 1)", con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet yourDefects = new DataSet();
            adapter.Fill(yourDefects);
            yourDefectsDataGrid.DataContext = yourDefects.Tables[0].DefaultView;
        }

        private void submitDefectButton_Click(object sender, RoutedEventArgs e)
        {
            string sqlIns = "INSERT INTO Trouble_Report (Date_Submitted, PersonId, Headline, Description, SoftwareSoftware_Id, Priority) VALUES (@Date_Submitted, @PersonId, @Headline, @Description, @SoftwareSoftware_Id, @Priority)";

            try
            {
                con.Open();
                SqlCommand cmdIns = new SqlCommand(sqlIns, con);
                cmdIns.Parameters.AddWithValue("@Date_Submitted", DateTime.Now);
                cmdIns.Parameters.AddWithValue("@PersonId", 0);
                cmdIns.Parameters.AddWithValue("@Headline", headlineInput.Text);
                cmdIns.Parameters.AddWithValue("@Description", descriptionInput.Text);
                cmdIns.Parameters.AddWithValue("@SoftwareSoftware_Id", softwareComboBox.SelectedValue);
                cmdIns.Parameters.AddWithValue("@Priority", priorityInput.SelectedItem.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", ""));
                cmdIns.ExecuteNonQuery();
                cmdIns.Dispose();
                cmdIns = null;
                con.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString(), ex);
            }
        }

        //Pop up a report window when the user double clicks the datagridview 
        private void DataGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            IInputElement element = e.MouseDevice.DirectlyOver;
            if (element != null && element is FrameworkElement)
            {
                if (((FrameworkElement)element).Parent is DataGridCell)
                {
                    var grid = sender as DataGrid;
                    if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
                    {
                        var rowView = grid.SelectedItem as DataRowView;
                        if (rowView != null)
                        {
                            DataRow row = rowView.Row;
                            Report report = new Report();
                            report.Title = "Defect ID: " + row.ItemArray[0].ToString();
                            report.reportNumber = Convert.ToInt32(row.ItemArray[0].ToString());
                            report.con = con;
                            report.Start();
                            report.Show();
                        }
                    }
                }
            }
        }

        private void glossaryGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void btnGlossarySearch_Click(object sender, RoutedEventArgs e)
        {
           string searchTerm = txtSearchTerm.Text.Trim();
           // if(!InputCheck.isSQLSafe(searchTerm))
           //{
           //    MessageBox.Show("Invalid input");
           //    return;
           //}

            if (ckbPartial.IsChecked == true)
            {
                string newSearchTerm = "%" + searchTerm + "%";
                searchTerm = newSearchTerm;
            }

            string query;

            if(cmbSearchBy.SelectedIndex == 0)
            {
                query = "SELECT dbo.Glossary.term AS term, dbo.Glossary.definition AS definition FROM dbo.GLOSSARY WHERE term LIKE \'" + searchTerm + "\';";
            }else{
                query = "SELECT dbo.Glossary.term AS term, dbo.Glossary.definition AS definition FROM dbo.GLOSSARY WHERE definition LIKE \'" + searchTerm + "\';";
            }

            SqlCommand glossarySearchCommand = new SqlCommand(query, con);
            SqlDataAdapter glossaryDataAdapter = new SqlDataAdapter(glossarySearchCommand);
            DataSet glossaryDataSet = new DataSet();
            glossaryDataAdapter.Fill(glossaryDataSet);
            glossaryGrid.DataContext = glossaryDataSet;

        }

        private void txtSearchTerm_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (String.IsNullOrEmpty(txtSearchTerm.Text.Trim()))
            {
                btnGlossarySearch.IsEnabled = false;
            }
            else
            {
                btnGlossarySearch.IsEnabled = true;
            }

        }

    }
}
